package yxy.game.pm2.module.pay;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

import yxy.apple.http.HTTPConnection;
import yxy.apple.http.request.JSONRequest;
import yxy.apple.http.response.JSONResponse;
import yxy.apple.logger.Logger;

public class PostUtil {

	private static final Logger logger = Logger.create(PostUtil.class);
	
	public static JSONObject response(String url, int timeout, JSONObject body) throws Exception {
		HTTPConnection connection = null;
		try {
			connection = new HTTPConnection(timeout);
			JSONRequest jsonRequest = new JSONRequest(url);
			jsonRequest.setHeader("Content-Type", "application/json");
			jsonRequest.setBody(body);
			JSONResponse response = connection.request(jsonRequest, JSONResponse.class);
			logger.info("---------------------" + response.toString());
			JSONObject result = response.body();
			return result;
		} catch (Exception e) {
			throw e;
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
	}
	
	public static NameValuePair[] getValuePair(JSONObject parseobj) {
		NameValuePair[] pair = new NameValuePair[parseobj.size()];

		Set<String> set = parseobj.keySet();
		int i = 0;
		for (String key : set) {
			pair[i] = new BasicNameValuePair(key, parseobj.getString(key));
			i++;
		}

		return pair;
	}
	
	/**
	 * 发送 POST 请求（HTTP），K-V形式
	 * @param apiUrl	API接口URL
	 * @param params    参数map
	 * @return
	 */
	public static String doPost(String apiUrl, NameValuePair[] params, int timeout) {
		return doPost(apiUrl, params, timeout, null);
	}

	public static String doPost(String apiUrl, NameValuePair[] params, int timeout, JSONObject headobj) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			if (headobj != null) {
				Set<String> keys = headobj.keySet();
				for (String key : keys) {
					httpPost.setHeader(key, headobj.getString(key));
				}
			}
			// -----------------
			RequestConfig.Builder configBuilder = RequestConfig.custom();
			// 设置连接超时
			configBuilder.setConnectTimeout(timeout);
			// 设置读取超时
			configBuilder.setSocketTimeout(timeout);
			// 设置从连接池获取连接实例的超时
			configBuilder.setConnectionRequestTimeout(timeout);
			// 在提交请求之前 测试连接是否可用
			configBuilder.setStaleConnectionCheckEnabled(true);
			httpPost.setConfig(configBuilder.build());
			// --------------
			List<NameValuePair> pairList = new ArrayList<NameValuePair>();
			if (params != null) {
				for (int i = 0; i < params.length; i++)
					pairList.add(params[i]);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
//			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}
}
